#!/bin/bash

# Docker容器管理脚本

TARGET_HOST="vistor@172.25.64.224"
CONTAINER_NAME="retail-frontend"

# 颜色输出
print_success() { echo -e "\033[32m✅ $1\033[0m"; }
print_error() { echo -e "\033[31m❌ $1\033[0m"; }
print_info() { echo -e "\033[34m📋 $1\033[0m"; }

# 显示帮助信息
show_help() {
    echo "Docker容器管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  status     - 查看容器状态"
    echo "  logs       - 查看容器日志"
    echo "  restart    - 重启容器"
    echo "  stop       - 停止容器"
    echo "  start      - 启动容器"
    echo "  remove     - 删除容器"
    echo "  shell      - 进入容器shell"
    echo "  info       - 查看容器详细信息"
    echo "  help       - 显示帮助信息"
}

# 查看容器状态
show_status() {
    print_info "查看容器状态..."
    ssh "$TARGET_HOST" "docker ps -a | grep $CONTAINER_NAME || echo '容器不存在'"
}

# 查看容器日志
show_logs() {
    print_info "查看容器日志..."
    ssh "$TARGET_HOST" "docker logs --tail 50 $CONTAINER_NAME"
}

# 重启容器
restart_container() {
    print_info "重启容器..."
    ssh "$TARGET_HOST" "docker restart $CONTAINER_NAME"
    print_success "容器重启完成"
}

# 停止容器
stop_container() {
    print_info "停止容器..."
    ssh "$TARGET_HOST" "docker stop $CONTAINER_NAME"
    print_success "容器停止完成"
}

# 启动容器
start_container() {
    print_info "启动容器..."
    ssh "$TARGET_HOST" "docker start $CONTAINER_NAME"
    print_success "容器启动完成"
}

# 删除容器
remove_container() {
    print_info "删除容器..."
    ssh "$TARGET_HOST" "docker stop $CONTAINER_NAME 2>/dev/null || true"
    ssh "$TARGET_HOST" "docker rm $CONTAINER_NAME"
    print_success "容器删除完成"
}

# 进入容器shell
enter_shell() {
    print_info "进入容器shell..."
    ssh -t "$TARGET_HOST" "docker exec -it $CONTAINER_NAME /bin/sh"
}

# 查看容器详细信息
show_info() {
    print_info "查看容器详细信息..."
    ssh "$TARGET_HOST" "docker inspect $CONTAINER_NAME"
}

# 主逻辑
case "$1" in
    "status")
        show_status
        ;;
    "logs")
        show_logs
        ;;
    "restart")
        restart_container
        ;;
    "stop")
        stop_container
        ;;
    "start")
        start_container
        ;;
    "remove")
        remove_container
        ;;
    "shell")
        enter_shell
        ;;
    "info")
        show_info
        ;;
    "help"|"--help"|"-h"|"")
        show_help
        ;;
    *)
        print_error "未知命令: $1"
        show_help
        exit 1
        ;;
esac

